// packageA/pages/staffTrajectory/staffTrajectory.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:{},
    //地区中心点-纬度
    latitude: '36.78466415549936',
    //地区中心点-经度
    longitude: '118.01429312179734',
    //地图上标记
    markers:[],
    //所有标记
    markersAll: [],
    //轨迹
    polyline: [],
    //轨迹数据
    lineArr:[],
    //统计到几天前
    dayNum:7,
    //日期选择框
    showDate:false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    //显示的日期
    currentDateStr:util.timeFormatDay(new Date()),
    //当前动画的点
    currentIndex: 0,
    //当前tab
    activeTab: 'times'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      
      console.log('人员轨迹传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj        
      })

      if(paramObj.workOverStartTime && paramObj.workOverEndTime){
        wx.setNavigationBarTitle({
		      title: '加班时段工作轨迹'
		    })
      }

      //获取轨迹数据
      //this.getTrajectoryData();
      this.getTrajectoryDataToMongodb();

      if(paramObj.lon && paramObj.lat){
        this.setData({
          longitude: paramObj.lon,
          latitude: paramObj.lat,
        }) 
      }else{
        this.setData({          
          longitude: '116.411168',
          latitude: '39.898331'
        })
      }
    }else{
      this.setData({          
        longitude: '116.411168',
        latitude: '39.898331'
      })
    }

    //设置统计几天数据
    this.getBeforeDate();  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //创建map上下文MapContext对象
    this.mapCtx = wx.createMapContext('map', this);
  },


 //获取轨迹数据
 getTrajectoryDataToMongodb(){
  let pObj=this.data.paramObj;

  Toast.loading({
    duration: 0,
    forbidClick: true,
    message: '加载中...'
  });

  //清空数据
  this.setData({ 
    lineArr: [],
    polyline:[]
  })  
  let param = {
    isAuth: false,
    className: 'wristbandLocation',
    data: {
      searchAll:true,
      selectFields: ['ctm', 'fix', 'lat', 'lon'],
      imei: pObj.imei,
      date :{">=":this.data.currentDateStr+" 00:00:00","<=":this.data.currentDateStr+" 23:59:59"},
      sort:{date:1}
    }
  }
  
  //从加班跳转来的，传参时间
  if(pObj.workOverStartTime && pObj.workOverEndTime){
    param.workOverStartTime=pObj.workOverStartTime;
    param.workOverEndTime=pObj.workOverEndTime;
  }

  console.log("param");
  console.log(param);
  
  CommonService.goFindList(param).then(res=>{
    Toast.clear();
    console.log("res");
    console.log(res);
    if(res.data.data && res.data.data.result){
      let result=res.data.data.result;
      console.log('轨迹数据');
      console.log(result);

      this.setData({ 
        lineArr: result
      })

      //显示当天所有数据的轨迹
      this.showAllTrajectory();
    }else{
      this.noTrajectory();
    }
    
  }).catch((error) => {
    this.noTrajectory();
  })    
},



  //获取轨迹数据
  getTrajectoryData(){
    let pObj=this.data.paramObj;

    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    //清空数据
    this.setData({ 
      lineArr: [],
      polyline:[]
    })  

    let param={
      imei: pObj.imei,
      at: this.data.currentDateStr
    }
    
    //从加班跳转来的，传参时间
    if(pObj.workOverStartTime && pObj.workOverEndTime){
      param.workOverStartTime=pObj.workOverStartTime;
      param.workOverEndTime=pObj.workOverEndTime;
    }

    CommonService.trajectoryRecord(param).then(res=>{
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.trajectory && res.data.data.result.trajectory.length){
        let result = []
        result=res.data.data.result.trajectory;
        console.log('轨迹数据');
        console.log(result);

        this.setData({ 
          lineArr: result
        })

        //显示当天所有数据的轨迹
        this.showAllTrajectory();
      }else{
        this.noTrajectory();
      }
      
    }).catch((error) => {
      this.noTrajectory();
    })    
  },

  //设置可选的最小日期
  getBeforeDate(){
    let rusult=util.countPrevDay(new Date(),this.data.dayNum);
    this.setData({ 
			minDate: rusult
		})  
  },

  //显示日期选择框
  onShowDate(){
    //加班跳转来的不能切换日期
    if(!this.data.paramObj.workOverStartTime){
      this.setData({
        showDate: true
      })
    }
  },

  //关闭日期选择框
  onCloseDate(){
    this.setData({ 
			showDate: false
		}) 
  },

  //确定日期时
  onConfirmDate(event){
    let currentDate=event.detail;
    this.setData({
      currentDate: currentDate,
      currentDateStr: util.timeFormatDay(currentDate)
    })

    //关闭日期选择框
    this.onCloseDate();
   
    //请求轨迹数据
    this.getTrajectoryDataToMongodb();
    //this.getTrajectoryData();
  },

  //显示当天所有数据的轨迹
  showAllTrajectory(){
    let lineArr=this.data.lineArr;
    let pointsArr=[],markers=[];

    //获取坐标
    lineArr.forEach(item => {
      pointsArr.push({
        longitude: item.lon,
        latitude: item.lat,
        ctm: item.ctm.substring(11,19)
      })
    });

    if(this.isOnePoint(pointsArr)){
      //如果全部数据相同
      markers.push({
        id: 0,
        latitude: pointsArr[0].latitude,
        longitude: pointsArr[0].longitude, 
        width: 30,
        height: 30,
        iconPath: 'http://bangnizu.oss-cn-hangzhou.aliyuncs.com/zhandouli/images/mark.png'
      });
    }else{
      pointsArr.forEach((item,index) => {
        markers.push({
          id: index,
          latitude: item.latitude,
          longitude: item.longitude, 
          width: 30,
          height: 30,
          title: item.ctm,
          iconPath: 'http://bangnizu.oss-cn-hangzhou.aliyuncs.com/zhandouli/images/mark.png'
        });
      });  
    }

    this.setData({
      markers: markers,
      markersAll: markers,
      polyline: [{
        points: pointsArr,
        color: "#1989FADD",
        width: 3,
        arrowLine: true
      }],      
      longitude: pointsArr[0].longitude,
      latitude: pointsArr[0].latitude  
    })

    //地图自适应缩放
    this.mapAdapt();
  },

  //判断轨迹数组中的值是否在一个点上
  isOnePoint(arr){
    let lng=arr[0].longitude;
    let lat=arr[0].latitude; 
    
    let lngFlag=arr.every(item=>{
      return item.longitude==lng;
    });

    let latFlag=arr.every(item=>{
      return item.latitude==lat;
    });
    
    if(lngFlag && latFlag){
      return true;
    }else{
      return false;
    }
  },

  //无轨迹
  noTrajectory(){
    Toast.fail('暂无轨迹数据');
    
    //把定位点显示到地图上
    this.setData({ 
      markers: [{
        id: 0,
        latitude: this.data.latitude,
        longitude: this.data.longitude      
      }]
    })
  },

  //地图自适应缩放
  mapAdapt(){
    let map=wx.createMapContext('map');
    map.includePoints({
      points: this.data.markers
    });
  }, 

  //移动点动画
  loopAnamation: function (subArray, index, markerId) {
    if(this.data.showMarkers){
      let that=this;
      this.mapCtx.translateMarker({
        markerId: 0,
        autoRotate: false,
        duration: 15000 / (subArray.length - 1),
        destination: {
          latitude: subArray[index].latitude,
          longitude: subArray[index].longitude,
        },
        animationEnd() {
          if(index < subArray.length-1){
            that.loopAnamation(subArray, index + 1, markerId);

            that.setData({
              currentIndex: index
            })
          }else{
            Toast.success('回放结束');            

            that.setData({
              markers: null,
              currentIndex: 0,
              activeTab: 'suspend'
            })

            //先清空markers，再赋值第一个点，不然会从终点移到起点
            setTimeout(() => {
              that.setData({
                markers: [subArray[0]]
              })
            }, 800);
          }          
        },
        fail: function (e) {
        }
      })
    }
  }, 

  //切换tab
  onChange(event) {
    let mark=event.detail;
    let arr1=this.data.markersAll;
    let arr2=this.data.markers;

    this.setData({
      activeTab: mark
    })

    if(mark=='times'){
      //显示所有标注
      this.setData({
        markers: null,
        showMarkers: false,
        currentIndex: 0
      })
     
      //先清空markers再赋值，不然会有一个点没有title
      setTimeout(() => {
        this.setData({
          markers: arr1
        })
      }, 300);

    }else if(mark=='plays'){
      //开始回放
      arr2[0].title=null;
      this.setData({ 
        showMarkers: true,
        markers: [arr2[0]]
      })
      this.loopAnamation(arr1, this.data.currentIndex, 0);

    }else if(mark=='suspend'){
      //暂停回放
      this.setData({
        showMarkers: false
      })
    }  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})